package trees;

import java.util.Stack;

public class RemoveDuplicates {
    public String removeDuplicates(String S) {
        Stack<String> stack = new Stack<>();
        int sLen = S.length();
        for (int i = 0; i < sLen; i++) {
            String val = String.valueOf(S.charAt(i));
            if (stack.isEmpty()) {
                stack.push(val);
            } else {
                String topVal = stack.peek();
                if (topVal.equals(val)) {
                    stack.pop();
                } else {
                    stack.push(val);
                }
            }
        }

        StringBuilder result = new StringBuilder();
        int stackSize = stack.size();
        for (int i = 0; i < stackSize; i++) {
            result.append(stack.pop());
        }

        return result.reverse().toString();
    }

    public static void main(String[] args) {
        String s = "abbaca";
        RemoveDuplicates removeDuplicates = new RemoveDuplicates();
        System.out.println(removeDuplicates.removeDuplicates(s));
    }
}
